﻿using Microsoft.Xaml.Interactivity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Demo06.Behaviors
{
    [Microsoft.Xaml.Interactivity.TypeConstraint(typeof(TextBox))]
    [Windows.UI.Xaml.Markup.ContentProperty(Name = "Actions")]
    class OnEnterBehavior : DependencyObject, IBehavior
    {
        public Windows.UI.Xaml.DependencyObject AssociatedObject { get; set; }

        public void Attach(Windows.UI.Xaml.DependencyObject associatedObject)
        {
            this.AssociatedObject = associatedObject;
            (this.AssociatedObject as TextBox).KeyDown += CommandOnEnterBehavior_KeyDown;
        }

        public void Detach()
        {
            (this.AssociatedObject as TextBox).KeyDown -= CommandOnEnterBehavior_KeyDown;
        }

        void CommandOnEnterBehavior_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
                foreach (IAction action in this.Actions)
                    action.Execute(this.AssociatedObject, null);
        }

        public ActionCollection Actions
        {
            get
            {
                var actions = (ActionCollection)GetValue(ActionsProperty);
                if (actions == null)
                    this.Actions = actions = new ActionCollection();
                return actions;
            }
            set { SetValue(ActionsProperty, value); }
        }
        public static readonly DependencyProperty ActionsProperty = DependencyProperty.Register("Actions", typeof(ActionCollection), typeof(OnEnterBehavior), null);
    }
}
